<% add_decidim_page_title(content_blocks_title) %>

<div class="card edit_content_blocks">
  <div class="item_show__header">
    <h1 class="item_show__header-title">
      <%= content_blocks_title %>

      <div class="relative">
        <button class="button button__sm button__secondary" data-controller="dropdown" data-target="add-content-block-dropdown">
          <%= add_content_block_text %>
          <%= icon "arrow-down-s-line", class: "!fill-white" %>
          <%= icon "arrow-down-s-line", class: "!fill-white" %>
        </button>

        <ul class="dropdown dropdown__bottom" id="add-content-block-dropdown" aria-hidden="true">
          <% available_manifests.each do |manifest| %>
            <li class="dropdown__item">
              <%= link_to t(manifest.public_name_key), resource_create_url(manifest.name), class: "dropdown__button", method: :post %>
            </li>
          <% end %>
        </ul>
      </div>
    </h1>
  </div>

  <div class="card-section-draggable-list">
    <div class="full">
      <div class="grid-x grid-margin-x card-grid">
        <div class="cell">
          <div class="card">
            <div class="card-section">
              <h5 class="draggable-list-title"><%= active_content_blocks_title %></h5>
              <ul class="draggable-list js-connect js-list-actives" data-sort-url="<%= resource_sort_url %>">
                <% active_blocks.each do |content_block| %>
                  <%= cell resource_content_block_cell, content_block %>
                <% end %>
              </ul>
            </div>
          </div>
        </div>
        <div class="cell">
          <div class="card">
            <div class="card-section">
              <h5 class="draggable-list-title"><%= inactive_content_blocks_title %></h5>

              <ul class="draggable-list js-connect js-list-available">
                <% inactive_blocks.each do |content_block_or_manifest| %>
                  <%= cell resource_content_block_cell, content_block_or_manifest %>
                <% end %>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
  document.addEventListener("dragend", function (event) {
    const activeBlocks = Array.prototype.slice.call(document.querySelectorAll(".js-list-actives li"));
    const activeBlocksId = activeBlocks.map(block => block.dataset.contentBlockId);

    $.ajax({
      method: "PUT",
      url: document.querySelector(".js-list-actives").dataset.sortUrl,
      contentType: "application/json",
      data: JSON.stringify({ ids_order: activeBlocksId })
    });
  })
</script>
